package com.daka.tools;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jay
 * <p>
 * When a user logins in, a session token is generated. User info will be stored by session token in memcache through
 * Visitor
 */
public final class SessionHolder {
    
    // User info for current user
    private static ThreadLocal<Visitor> sessions = new ThreadLocal<Visitor>();
    
    // Session token being generated whenever a user logins in
    private static ThreadLocal<String> token = new ThreadLocal<>();
    
    // Store openId for wechat user
    private static ThreadLocal<String> openId = new ThreadLocal<String>();
    
    private static ConcurrentHashMap baseToken = new ConcurrentHashMap();
    
    private static ConcurrentHashMap<String, HashMap<String, String>> userSession = new ConcurrentHashMap<>();
    
    public static ConcurrentHashMap<String, HashMap<String, String>> getUserSession() {
        return userSession;
    }
    
    public static void setUserSession(String sessionId, HashMap<String, String> userHash) {
        userSession.put(sessionId, userHash);
    }
    
    public static String getBaseToken() {
        if (baseToken.get("token") == null) {
            return "";
        } else {
            return baseToken.get("token").toString();
        }
        
    }
    
    public static void setBaseToken(String token) {
        baseToken.put("token", token);
    }
    
    public static Visitor get() {
        return sessions.get();
    }
    
    public static void set(Visitor visitor) {
        sessions.set(visitor);
    }
    
    public static void clearSession() {
        sessions.set(null);
    }
    
    public static String getToken() {
        return token.get();
    }
    
    public static void setToken(String t) {
        token.set(t);
    }
    
    public static void clearToken() {
        token.set(null);
    }
    
    public static String getOpenId() {
        return openId.get();
    }
    
    public static void setOpenId(String id) {
        openId.set(id);
    }
    
    public static void clearOpenId() {
        openId.set(null);
    }
    
    public static void clearSessionHolder() {
        clearOpenId();
        clearToken();
        sessions.set(null);
    }
    
}
